package com.example.android.shanwei

import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView

class MyAdapter (val datas:List<Scenery>): RecyclerView.Adapter<MyAdapter.ViewHolder>() {
    //在子项布局当中进行控件封装
    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var image:ImageView=itemView.findViewById(R.id.image)
        var name:TextView=itemView.findViewById(R.id.name)
        var brief:TextView=itemView.findViewById(R.id.brief)
    }
    //加载子项布局
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyAdapter.ViewHolder {
        var view = LayoutInflater.from(parent.context).inflate(R.layout.item, parent, false)
        val viewHolder=ViewHolder(view)
        //点击子项目实现跳转
        view.setOnClickListener{
            val position=viewHolder.adapterPosition
            val brief=datas.get(position).brief
            val name=datas.get(position).name
            val image=datas.get(position).image
            Toast.makeText(parent.context,name+"详情页",Toast.LENGTH_SHORT).show()
            val intent=Intent(view.getContext(),ItemActivity::class.java)
            intent.putExtra("image",image)
            intent.putExtra("name",name)
            intent.putExtra("brief",brief)
            view.context.startActivity(intent)
        }
        return viewHolder
    }

    //数据和控件之间的关联绑定
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        var scenery:Scenery=datas.get(position)
        holder.image.setImageResource(scenery.image)
        holder.name.setText(scenery.name)
        holder.brief.setText(scenery.brief)
    }
    //返回子项个数
    override fun getItemCount()=datas.size
}